陣列由小到大排序

#C#

Posted by Phyxsius on 2023-09-16


internal class Program
{
    private static void Main(string[] args)
    {
        int[] ary = { 1, 2, 7, 3, 4};

        Console.WriteLine("原始陣列內容:");
        showArray(ary);

        for (int i=0; i<ary.Length; i++)
        {
            for(int j=0; j<ary.Length; j++)
            {
                if (ary[i] < ary[j])
                {
                    swap(ary, i, j);
                }
            }
        }

        Console.WriteLine("由小到大排序後陣列內容:");
        showArray(ary);
    }

    //兩個值互相交換
    static void swap(int[] ary, int value1, int value2)
    {
        int tmp = ary[value2];
        ary[value2] = ary[value1];
        ary[value1] = tmp;
    }

    //顯示陣列內容
    static void showArray(int[] ary)
    {
        for (int i=0; i<ary.Length; i++)
        {
            Console.Write(ary[i] + ",");
        }
        Console.WriteLine();
    }
}

#C#







Related Posts

Nand2tetris第一週心得

Nand2tetris第一週心得

為你的 Github 首頁加上酷酷的貪吃蛇動畫

為你的 Github 首頁加上酷酷的貪吃蛇動畫

Express 框架 - debug 補

Express 框架 - debug 補


Comments